import { EventNameConst } from '@/constants/framework/event-emitter-const'
type EventName = typeof EventNameConst[number] | `Custom:${string}`
class EventEmitter {
    // 使用 Map 存储事件
    private events: Map<EventName, Function[]>;
    constructor() {
        this.events = new Map();
    }
    /**
     * @description 监听事件，且事件具有排序功能
     * @params event 事件名称, 自定义事件以 Custom: 开头
     * @params cb 回调函数
     * @params index 回调函数在事件中的位置，默认为末尾
     */
    on(event: EventName, cb: Function, index?: number) {
        if (!this.events.has(event)) {
            this.events.set(event, []);
        }
        const callbacks = this.events.get(event);
        if (callbacks && index === undefined) {
            callbacks.push(cb);
        } else if (callbacks && index !== undefined) {
            callbacks.splice(index, 0, cb);
        }
    }
    // 触发事件，且按事件注册顺序执行，需要注意异步问题
    async emit(event: EventName, ...args: any[]) {
        const callbacks = this.events.get(event);
        if (callbacks) {
            for (const cb of callbacks) {
                await cb(...args);
            }
        } else {
            return false
        }
    }
    // 移除事件
    off(event: EventName, cb: Function) {
        const callbacks = this.events.get(event);
        if (callbacks) {
            this.events.set(event, callbacks.filter(item => item !== cb));
        }
    }
    // 移除所有事件
    offAll(event: EventName) {
        this.events.delete(event);
    }
}
export default new EventEmitter()
